package cn.edu.zstu.qingzhu.qingzhushop.entity;

import cn.edu.zstu.qingzhu.qingzhushop.common.Constants;
import com.baomidou.mybatisplus.core.conditions.interfaces.Func;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.util.StringUtils;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-11-08 19:02
 */
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "查询DTO", description = "")
public class QueryModel<T> implements IGenerative<T> {
    private Integer showCount = 1;
    private Integer current = Constants.GOODS_SEARCH_PAGE_LIMIT;
    private String sortName;
    private String sortOrder;

    public <T> Page<T> newPage() {
        Page page = new Page();
        page.setCurrent(current <= 0 ? 1 : current);
        page.setSize(showCount <= 0 || showCount > 100 ? Constants.GOODS_SEARCH_PAGE_LIMIT : showCount);
        return page;
    }

    @Override
    public T generate() {
        return generate((T) new QueryModel<T>());
    }

    @Override
    public T generate(T wrapper) {
        if (wrapper instanceof Func) {
            Func queryWrapper = (Func) wrapper;
            if (!StringUtils.isEmpty(sortName) && !StringUtils.isEmpty(sortOrder)) {
                if ("ASC".equals(sortOrder.toUpperCase())) {
                    queryWrapper.orderByAsc(sortName);
                } else if ("DESC".equals(sortOrder.toUpperCase())) {
                    queryWrapper.orderByDesc(sortName);
                } else {
                    queryWrapper.orderByAsc(sortName);
                }
            } else {
                queryWrapper.orderByAsc(sortName);
            }
            return (T) queryWrapper;
        }
        return wrapper;
    }
}
